<?php

declare(strict_types=1);

namespace App\Api\Service;

use App\Exception\DefaultException;
use App\Model\Member;
use App\Utils\WechatMiniApp;

use Throwable;

class AuthService
{
    /**
     * 登录
     * @param array $params
     * @return array
     */
    public function login(array $params): array
    {
        try {
            // 小程序登录
            $openid = (new WechatMiniApp())->codeToSession($params['code'])['openid'];

            // 查询或创建用户
            $member = Member::firstOrCreate([
                'openid' => $openid,
            ], [
                'avatar' => $params['avatar'],
                'nickname' => $params['nickname'],
            ]);

            // 生成Token
            $token = user('api')->getToken([
                'id' => $member->id,
            ]);

            return [
                'token' => $token,
            ];
        } catch (Throwable $e) {
            business_error_logger(__FUNCTION__, $e);
            throw new DefaultException('登录失败，请稍后重试'.$e->getMessage());
        }
    }
}
